package com.hifar.test.entrust.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ZipUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hifar.log.AutoLogUtils;
import com.hifar.plat.baseModal.pojo.BaseOssFiles;
import com.hifar.plat.baseModal.service.IBaseOssFilesService;
import com.hifar.plat.dept.pojo.BaseOrgDeptPlat;
import com.hifar.plat.dept.service.IBaseOrgDeptPlatService;
import com.hifar.plat.user.pojo.BaseOrgUserPlat;
import com.hifar.plat.user.service.IBaseOrgUserService;
import com.hifar.sys.MinioUtil;
import com.hifar.test.entrust.constant.*;
import com.hifar.test.entrust.mapper.HfEnvGKEntrustMapper;
import com.hifar.test.entrust.model.EntrustPieceQrData;
import com.hifar.test.entrust.model.EntrustProjectQrData;
import com.hifar.test.entrust.model.EntrustQRData;
import com.hifar.test.entrust.pojo.*;
import com.hifar.test.entrust.pojo.VO.*;
import com.hifar.test.entrust.service.IHfEnvGkEntrustService;
import com.hifar.test.entrust.service.IHfEnvGkPieceService;
import com.hifar.test.entrust.service.IHfEnvGkProjectService;
import com.hifar.test.standardbase.pojo.HfResStandard;
import com.hifar.test.standardbase.service.IHfResStandardService;
import com.hifar.test.task.pojo.HfEnvTask;
import com.hifar.test.task.pojo.VO.HfEnvTaskTestVO;
import com.hifar.test.task.service.IHfEnvTaskService;
import com.hifar.test.test.service.IHfEnvTestService;
import com.hifar.test.unit.pojo.HfPrjUnitBase;
import com.hifar.test.unit.service.IHfPrjUnitBaseService;
import com.hifar.utils.FileUtil;
import com.hifar.utils.ToolKit;
import com.tssk.kylx.fw.utils.id.IdUtils;
import com.tssk.kylx.fwx.xutils.consts.SysConsts;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 委托单
 */
@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
public class HfEnvGkEntrustServiceImpl extends ServiceImpl<HfEnvGKEntrustMapper, HfEnvGkEntrust> implements IHfEnvGkEntrustService {

    @Autowired
    private AutoLogUtils autoLogUtils;
    @Autowired
    private IBaseOssFilesService baseOssFilesService;
    @Autowired
    private IHfEnvGkPieceService gkPieceService;
    @Autowired
    private IHfEnvGkProjectService gkProjectService;
    @Autowired
    private IHfPrjUnitBaseService unitBaseService;
    @Autowired
    private IHfEnvTaskService taskService;
    @Autowired
    private IHfEnvTestService testService;

    @Autowired
    private IHfResStandardService standardService;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private IBaseOrgUserService baseOrgUserService;
    @Autowired
    private IBaseOrgDeptPlatService baseOrgDeptPlatService;


    @Override
    public void manualInputTask(HfEnvGkEntrustSaveVO manualInputTaskVO) {
        HfEnvGkEntrust hfEnvGkEntrust = new HfEnvGkEntrust();
        BeanUtils.copyProperties(manualInputTaskVO, hfEnvGkEntrust);

        String entrustCode = manualInputTaskVO.getEntrustCode();

        HfEnvGkEntrust hisGkEntrust = this.lambdaQuery()
                .eq(HfEnvGkEntrust::getEntrustCode, entrustCode)
                .one();
        String mainId = null;
        if (Objects.nonNull(hisGkEntrust)) {
            String status = hisGkEntrust.getStatus();
            if (Arrays.asList(EntrustConsts.WTD_STATUS_YWC, EntrustConsts.WTD_STATUS_YQX, EntrustConsts.WTD_STATUS_YZZ, EntrustConsts.WTD_STATUS_CANCEL)
                    .contains(status)) {
                throw new RuntimeException("该委托单号已完成,请检查!");
            }
            mainId = hisGkEntrust.getId();
            hfEnvGkEntrust.setId(mainId);
            hfEnvGkEntrust.setCreateTime(hisGkEntrust.getCreateTime());
            hfEnvGkEntrust.setCreateUserId(hisGkEntrust.getCreateUserId());
            hfEnvGkEntrust.setCreateUserName(hisGkEntrust.getCreateUserName());
            this.updateById(hfEnvGkEntrust);
        } else {
            // 工控网建的委托单默认审批通过
            hfEnvGkEntrust.setStatus(EntrustConsts.WTD_STATUS_SPTG);
            this.save(hfEnvGkEntrust);
            mainId = hfEnvGkEntrust.getId();
        }
        List<BaseOssFiles> testOutlineFileList = Optional.ofNullable(manualInputTaskVO.getTestOutlineFileList())
                .orElse(new ArrayList<>(0));
        for (BaseOssFiles baseOssFiles : testOutlineFileList) {
            baseOssFiles.setRefId(mainId);
            baseOssFiles.setRefType(EntrustConsts.WTD_OUTLINE_REF_TYPE);
        }

        UpdateWrapper<BaseOssFiles> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda()
                .set(BaseOssFiles::getRefId, null)
                .eq(BaseOssFiles::getRefId, mainId)
                .eq(BaseOssFiles::getRefType, EntrustConsts.WTD_OUTLINE_REF_TYPE);
        baseOssFilesService.update(updateWrapper);
        baseOssFilesService.updateBatchById(testOutlineFileList);

        String productName = null;
        // 保存子表
        List<HfEnvGkPiece> gkPieceList = manualInputTaskVO.getPieceInfo();
        if (gkPieceList != null && gkPieceList.size() > 0) {
            for (int i = 0; i < gkPieceList.size(); i++) {
                HfEnvGkPiece item = gkPieceList.get(i);
                item.setId(null);
                item.setGkEntrustId(mainId);
                item.setSecretLevel(1);
                item.setStatus(PieceConsts.PIECE_STATUS_CG);
                item.setEntrustCode(entrustCode);
                item.setRowSort(i);
            }
            productName = gkPieceList.get(0).getProductName();
        }
        gkPieceService.removeByGkEntrustId(mainId);
        gkPieceService.saveBatch(gkPieceList);
        // 保存子表
        List<HfEnvGkProjectSaveVO> gkProjectList = Optional.ofNullable(manualInputTaskVO.getProjectInfo()).orElse(new ArrayList<>());

        List<HfEnvTask> taskList = new ArrayList<>(gkProjectList.size());

        gkProjectService.removeByGkEntrustId(mainId);
        taskService.removeByGkEntrustId(mainId);
        if (gkProjectList.size() > 0) {
            for (int i = 0; i < gkProjectList.size(); i++) {
                HfEnvGkProjectSaveVO gkProjectSaveVO = gkProjectList.get(i);
                List<BaseOssFiles> testPhotoList = Optional.ofNullable(gkProjectSaveVO.getTestPhotoList())
                        .orElse(new ArrayList<>());



                HfEnvGkProject hfEnvGkProject = new HfEnvGkProject();
                BeanUtil.copyProperties(gkProjectSaveVO,hfEnvGkProject);

                hfEnvGkProject.setId(null);
                hfEnvGkProject.setGkEntrustId(mainId);
                hfEnvGkProject.setRowSort(i);
                gkProjectService.save(hfEnvGkProject);
                String gkProjectId = hfEnvGkProject.getId();

                for (BaseOssFiles testPhotoFile : testPhotoList) {
                    testPhotoFile.setRefId(gkProjectId);
                    testPhotoFile.setRefType(EntrustConsts.WTD_TEST_PHONE);
                }

                UpdateWrapper<BaseOssFiles> testPhoneUpdateWrapper = new UpdateWrapper<>();
                testPhoneUpdateWrapper.lambda()
                        .set(BaseOssFiles::getRefId, null)
                        .eq(BaseOssFiles::getRefId, gkProjectId)
                        .eq(BaseOssFiles::getRefType, EntrustConsts.WTD_TEST_PHONE);
                baseOssFilesService.update(testPhoneUpdateWrapper);
                baseOssFilesService.updateBatchById(testPhotoList);


                String unitId = gkProjectSaveVO.getUnitId();
                HfPrjUnitBase hfPrjUnitBase = unitBaseService.getById(unitId);

                HfEnvTask hfEnvTask = new HfEnvTask();
                hfEnvTask.setGkProjectId(gkProjectId);
                hfEnvTask.setIzExtAssistance(ExtAssistanceConsts.NO_EXT_ASSISTANCE);
                hfEnvTask.setStandardId(gkProjectSaveVO.getStandardId());
                hfEnvTask.setStandardCode(gkProjectSaveVO.getStandardCode());
                hfEnvTask.setStandardName(gkProjectSaveVO.getStandardName());
                hfEnvTask.setUnitId(gkProjectSaveVO.getUnitId());
                hfEnvTask.setUnitCode(hfPrjUnitBase.getUnitCode());
                hfEnvTask.setUnitName(hfPrjUnitBase.getUnitName());
                hfEnvTask.setGkEntrustId(mainId);
                hfEnvTask.setUnitTypeName(hfPrjUnitBase.getClassifyName());
                hfEnvTask.setTestCondition(gkProjectSaveVO.getTestCondition());
                hfEnvTask.setEntrustCode(entrustCode);
                hfEnvTask.setStatus(TaskConsts.TASK_STATUS_CG);
                hfEnvTask.setRowSort(i);
                String taskCode = String.format("%s%s", entrustCode, ToolKit.supplementZero(String.valueOf(i + 1), 2));
                hfEnvTask.setTaskCode(taskCode);
                taskList.add(hfEnvTask);
            }
        }
        taskService.saveBatch(taskList);
    }


    @Override
    public void refreshEntrustStatus(String taskId) {
        HfEnvTask hfEnvTask = taskService.getById(taskId);
        Assert.notNull(hfEnvTask, "任务数据不存在!");
        String status = hfEnvTask.getStatus();
        String gkEntrustId = hfEnvTask.getGkEntrustId();
        HfEnvGkEntrust hfEnvGkEntrust = this.getById(gkEntrustId);
        Assert.notNull(hfEnvGkEntrust, "委托数据不存在!");
        String gkEntrustStatus = hfEnvGkEntrust.getStatus();

        List<HfEnvTask> taskList = taskService.lambdaQuery()
                .eq(HfEnvTask::getGkEntrustId, gkEntrustId)
                .list();
        List<String> taskStatusList = taskList.stream()
                .map(HfEnvTask::getStatus)
                .distinct()
                .collect(Collectors.toList());
        boolean isFinish = taskStatusList.contains(TaskConsts.TASK_STATUS_FINISH) && taskStatusList.stream().anyMatch(
                item -> Arrays.asList(TaskConsts.TASK_STATUS_FORCE_END, TaskConsts.TASK_STATUS_FINISH).contains(item)
        );
        if (isFinish) {
            gkEntrustStatus = EntrustConsts.WTD_STATUS_YWC;
        } else {
            // 已通过审核，且该委托单下所有任务单均为未分配已分配状态。
            boolean isPass = taskStatusList.stream()
                    .allMatch(item -> Arrays.asList(TaskConsts.TASK_STATUS_CG, TaskConsts.TASK_STATUS_YFP).contains(item));

            gkEntrustStatus = EntrustConsts.WTD_STATUS_SPTG;
        }
        this.lambdaUpdate()
                .set(HfEnvGkEntrust::getStatus, gkEntrustStatus)
                .eq(HfEnvGkEntrust::getId, gkEntrustId)
                .update();
    }

    @Override
    public void saveEntrustFromQRCode(EntrustQRData entrustQRData) {
        HfEnvGkEntrust hfEnvGkEntrust = new HfEnvGkEntrust();

        String entrustCode = entrustQRData.getEntrustCode();

        HfEnvGkEntrust hisEntrust = this.lambdaQuery()
                .eq(HfEnvGkEntrust::getEntrustCode, entrustCode)
                .one();
        Assert.isNull(hisEntrust, "委托单:" + entrustCode + "已导入,请勿重复导入!");

        BeanUtils.copyProperties(entrustQRData, hfEnvGkEntrust);
        hfEnvGkEntrust.setStatus(EntrustConsts.WTD_STATUS_SPTG);
        hfEnvGkEntrust.setId(null);


        String entrustCustCode = entrustQRData.getEntrustCustCode();
        String entrustUserCode = entrustQRData.getEntrustUserCode();


        List<BaseOrgUserPlat> userPlatList = baseOrgUserService.lambdaQuery()
            .eq(BaseOrgUserPlat::getUserCode, entrustUserCode)
            .ne(BaseOrgUserPlat::getStatus, SysConsts.LOGIC_DELETE)
            .list();
        Assert.notEmpty(userPlatList, String.format("用户编号:%s不存在!", entrustUserCode));
        BaseOrgUserPlat baseOrgUserPlat = userPlatList.get(0);
        hfEnvGkEntrust.setEntrustUserId(baseOrgUserPlat.getId());
        hfEnvGkEntrust.setEntrustUserName(baseOrgUserPlat.getIdName());

        List<BaseOrgDeptPlat> deptPlatList = baseOrgDeptPlatService.lambdaQuery()
            .eq(BaseOrgDeptPlat::getDeptCode, entrustCustCode)
            .ne(BaseOrgDeptPlat::getStatus, SysConsts.LOGIC_DELETE)
            .list();
        Assert.notEmpty(deptPlatList, String.format("部门编号:%s不存在!", entrustCustCode));

        BaseOrgDeptPlat baseOrgDeptPlat = deptPlatList.get(0);
        hfEnvGkEntrust.setEntrustCustId(baseOrgDeptPlat.getId());
        hfEnvGkEntrust.setEntrustCust(baseOrgDeptPlat.getDeptName());


        this.save(hfEnvGkEntrust);
        String id = hfEnvGkEntrust.getId();
        List<EntrustPieceQrData> qrPieceList = Optional.ofNullable(entrustQRData.getPieceList()).orElse(new ArrayList<>());
        List<EntrustProjectQrData> qrProjectList = Optional.ofNullable(entrustQRData.getProjectList()).orElse(new ArrayList<>());

        List<HfEnvGkPiece> gkPieceList = new ArrayList<>();
        for (EntrustPieceQrData entrustPieceQrData : qrPieceList) {
            HfEnvGkPiece hfEnvGkPiece = new HfEnvGkPiece();
            BeanUtils.copyProperties(entrustPieceQrData, hfEnvGkPiece);
            hfEnvGkPiece.setId(null);
            hfEnvGkPiece.setGkEntrustId(id);
            gkPieceList.add(hfEnvGkPiece);
        }

        List<HfEnvTask> taskList = new ArrayList<>();

        for (int i = 0; i < qrProjectList.size(); i++) {
            EntrustProjectQrData entrustProjectQrData = qrProjectList.get(i);
            HfEnvGkProject hfEnvGkProject = new HfEnvGkProject();
            BeanUtils.copyProperties(entrustProjectQrData, hfEnvGkProject);
            hfEnvGkProject.setId(null);
            hfEnvGkProject.setGkEntrustId(id);

            String unitCode = hfEnvGkProject.getUnitCode();
            HfPrjUnitBase hfPrjUnitBase = unitBaseService.getOneByCode(unitCode);
            Assert.notNull(hfPrjUnitBase, String.format("项目【%s】未定义!", unitCode));

            hfEnvGkProject.setStandardId(hfEnvGkProject.getStandardId());
            hfEnvGkProject.setStandardCode(hfEnvGkProject.getStandardCode());
            hfEnvGkProject.setStandardName(hfEnvGkProject.getStandardName());

            hfEnvGkProject.setUnitId(hfPrjUnitBase.getId());
            hfEnvGkProject.setUnitCode(hfPrjUnitBase.getUnitCode());
            hfEnvGkProject.setUnitName(hfPrjUnitBase.getUnitName());
            gkProjectService.save(hfEnvGkProject);
            String gkProjectId = hfEnvGkProject.getId();



            HfEnvTask hfEnvTask = new HfEnvTask();
            hfEnvTask.setGkProjectId(gkProjectId);
            hfEnvTask.setIzExtAssistance(ExtAssistanceConsts.NO_EXT_ASSISTANCE);
            hfEnvTask.setStandardId(hfEnvGkProject.getStandardId());
            hfEnvTask.setStandardCode(hfEnvGkProject.getStandardCode());
            hfEnvTask.setStandardName(hfEnvGkProject.getStandardName());
            hfEnvTask.setUnitId(hfPrjUnitBase.getId());
            hfEnvTask.setUnitCode(hfPrjUnitBase.getUnitCode());
            hfEnvTask.setUnitName(hfPrjUnitBase.getUnitName());
            hfEnvTask.setGkEntrustId(id);
            hfEnvTask.setUnitTypeName(hfPrjUnitBase.getClassifyName());
            hfEnvTask.setTestCondition(hfEnvGkProject.getTestCondition());
            hfEnvTask.setEntrustCode(entrustCode);
            hfEnvTask.setStatus(TaskConsts.TASK_STATUS_CG);
            hfEnvTask.setRowSort(i);
            String taskCode = String.format("%s%s", entrustCode, ToolKit.supplementZero(String.valueOf(i + 1), 2));
            hfEnvTask.setTaskCode(taskCode);
            taskList.add(hfEnvTask);
        }

        gkPieceService.saveBatch(gkPieceList);
        taskService.saveBatch(taskList);
    }


    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NOT_SUPPORTED)
    public void importDataPackage(String fileId) throws Exception {
        BaseOssFiles baseOssFiles = baseOssFilesService.getById(fileId);
        Assert.notNull(baseOssFiles, "附件不存在!");

        String tempPath = FileUtil.getTempPath();
        String baseTempPath = tempPath + File.separator + IdUtils.uuid32();
        File baseTempFile = new File(baseTempPath);
        if (!baseTempFile.exists()) {
            baseTempFile.mkdirs();
        }
        String zipDownloadPath = tempPath + File.separator + IdUtils.uuid32() + ".zip";
        String bucketPre = baseOssFiles.getBucketPre();
        String filePath = baseOssFiles.getFilePath();
        try {
            MinioUtil.downloadFileToLocal(bucketPre, filePath, zipDownloadPath);
            File unzip = ZipUtil.unzip(new File(zipDownloadPath));
            Assert.notNull(unzip, "解压文件失败!");
            String zipBasePath = unzip.getAbsolutePath();
            String entrustDataFilePath = zipBasePath + File.separator + DataPackageConsts.ENTRUST_FILE_NAME;
            String pieceDataFilePath = zipBasePath + File.separator + DataPackageConsts.PIECE_FILE_NAME;
            String projectDataFilePath = zipBasePath + File.separator + DataPackageConsts.PROJECT_FILE_NAME;
            String fileDataFilePath = zipBasePath + File.separator + DataPackageConsts.FILE_FILE_NAME;

            File entrustDataFile = new File(entrustDataFilePath);
            File pieceDataFile = new File(pieceDataFilePath);
            File projectDataFile = new File(projectDataFilePath);
            File fileDataFile = new File(fileDataFilePath);
            Assert.isTrue(entrustDataFile.exists(), "数据包文件缺失!");
            Assert.isTrue(pieceDataFile.exists(), "数据包文件缺失!");
            Assert.isTrue(projectDataFile.exists(), "数据包文件缺失!");

            String entrustDataText = ToolKit.readFile(entrustDataFile);
            String pieceDataText = ToolKit.readFile(pieceDataFile);
            String projectDataText = ToolKit.readFile(projectDataFile);
            String fileDataText = ToolKit.readFile(fileDataFile);

            // 添加调试日志
            System.out.println("=== 文件读取调试信息 ===");
            System.out.println("委托数据文件编码检测完成，内容长度: " + (entrustDataText != null ? entrustDataText.length() : 0));
            System.out.println("委托数据内容前100字符: " +
                    (entrustDataText != null && entrustDataText.length() > 100 ?
                            entrustDataText.substring(0, 100) : entrustDataText));
            System.out.println("样品数据内容长度: " + (pieceDataText != null ? pieceDataText.length() : 0));
            System.out.println("项目数据内容长度: " + (projectDataText != null ? projectDataText.length() : 0));
            System.out.println("文件数据内容长度: " + (fileDataText != null ? fileDataText.length() : 0));
            System.out.println("========================");

            Files.walk(Paths.get(zipBasePath))
                    .filter(Files::isRegularFile)
                    .forEach(item -> {
                        File tempFile = item.toFile();
                        String absolutePath = tempFile.getAbsolutePath();
                        Path fileName = item.getFileName();

                        String baseFilePath = absolutePath.substring(absolutePath.indexOf(zipBasePath) + zipBasePath.length() + 1)
                                .replace("\\", "/");
                        String[] filePathArr = baseFilePath.split("/", 2);
                        String fileBucketPre = filePathArr[0]; // 第一层路径
                        String objectName = filePathArr.length > 1 ? filePathArr[1] : null; // 剩余路径（如果有）
                        if (Objects.isNull(objectName)) {
                            return;
                        }
                        try {
                            log.debug(String.format("文件【%s】上传至【%s】的【%s】", fileName, fileBucketPre, objectName));
                            if (fileName.endsWith(".pdf")) {
                                MinioUtil.uploadLocalFileToMinio(fileBucketPre, objectName, absolutePath, "application/pdf");
                            } else {
                                MinioUtil.uploadLocalFileToMinio(fileBucketPre, objectName, absolutePath);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    });
            // 使用注入的ObjectMapper实例，确保字符编码配置正确
            System.out.println("开始JSON解析，使用配置的ObjectMapper");
            HfEnvEntrustDataPackageVO hfEnvEntrustDataPackageVO = objectMapper.readValue(entrustDataText, HfEnvEntrustDataPackageVO.class);
            List<HfEnvPiece> pieceList = objectMapper.readValue(pieceDataText, new TypeReference<List<HfEnvPiece>>() {

            });
            List<HfEnvProject> projectList = objectMapper.readValue(projectDataText, new TypeReference<List<HfEnvProject>>() {
            });

            List<BaseOssFiles> baseOssFileList = objectMapper.readValue(fileDataText, new TypeReference<List<BaseOssFiles>>() {
            });

            System.out.println("JSON解析完成，委托单号: " + hfEnvEntrustDataPackageVO.getEntrustCode());
            String entrustCustCode = hfEnvEntrustDataPackageVO.getEntrustCustCode();
            String entrustUserCode = hfEnvEntrustDataPackageVO.getEntrustUserCode();

            List<BaseOrgUserPlat> userPlatList = baseOrgUserService.lambdaQuery()
                .eq(BaseOrgUserPlat::getUserCode, entrustUserCode)
                .ne(BaseOrgUserPlat::getStatus, SysConsts.LOGIC_DELETE)
                .list();
            Assert.notEmpty(userPlatList, String.format("用户编号:%s不存在!", entrustUserCode));
            BaseOrgUserPlat baseOrgUserPlat = userPlatList.get(0);
            hfEnvEntrustDataPackageVO.setEntrustUserId(baseOrgUserPlat.getId());
            hfEnvEntrustDataPackageVO.setEntrustUserName(baseOrgUserPlat.getIdName());

            List<BaseOrgDeptPlat> deptPlatList = baseOrgDeptPlatService.lambdaQuery()
                .eq(BaseOrgDeptPlat::getDeptCode, entrustCustCode)
                .ne(BaseOrgDeptPlat::getStatus, SysConsts.LOGIC_DELETE)
                .list();
            Assert.notEmpty(deptPlatList, String.format("部门编号:%s不存在!", entrustCustCode));

            BaseOrgDeptPlat baseOrgDeptPlat = deptPlatList.get(0);
            hfEnvEntrustDataPackageVO.setEntrustCustId(baseOrgDeptPlat.getId());

            HfEnvGkEntrust hfEnvGkEntrust = new HfEnvGkEntrust();
            BeanUtils.copyProperties(hfEnvEntrustDataPackageVO, hfEnvGkEntrust);
            hfEnvGkEntrust.setId(null);
            String entrustCode = hfEnvGkEntrust.getEntrustCode();
            boolean codeExist = this.existEntrustCode(entrustCode);
            Assert.isTrue(!codeExist, String.format("委托单号:%s已存在!", entrustCode));
            this.save(hfEnvGkEntrust);
            String gkEntrustId = hfEnvGkEntrust.getId();

            List<HfEnvGkPiece> gkPieceList = new ArrayList<>();
            for (HfEnvPiece hfEnvPiece : pieceList) {
                HfEnvGkPiece hfEnvGkPiece = new HfEnvGkPiece();
                BeanUtils.copyProperties(hfEnvPiece, hfEnvGkPiece);
                hfEnvGkPiece.setId(null);
                hfEnvGkPiece.setGkEntrustId(gkEntrustId);
                hfEnvGkPiece.setEntrustId(null);
                hfEnvGkPiece.setCreateUserId(null);
                hfEnvGkPiece.setCreateTime(null);
                hfEnvGkPiece.setCreateUserName(null);
                hfEnvGkPiece.setUpdateTime(null);
                hfEnvGkPiece.setUpdateUserId(null);
                hfEnvGkPiece.setUpdateUserName(null);
                gkPieceList.add(hfEnvGkPiece);
            }

            gkPieceService.saveBatch(gkPieceList);

            for (BaseOssFiles hfBaseOssFiles : baseOssFileList) {
                hfBaseOssFiles.setRefId(gkEntrustId);
                hfBaseOssFiles.setId(null);
                hfBaseOssFiles.setCreateUserId(null);
                hfBaseOssFiles.setCreateTime(null);
                hfBaseOssFiles.setCreateUserName(null);
                hfBaseOssFiles.setUpdateTime(null);
                hfBaseOssFiles.setUpdateUserId(null);
                hfBaseOssFiles.setUpdateUserName(null);
            }
            baseOssFilesService.saveBatch(baseOssFileList);


            List<HfEnvTask> taskList = new ArrayList<>();

            for (int i = 0; i < projectList.size(); i++) {
                HfEnvProject hfEnvProject = projectList.get(i);

                HfEnvGkProject hfEnvGkProject = new HfEnvGkProject();
                BeanUtils.copyProperties(hfEnvProject, hfEnvGkProject);
                hfEnvGkProject.setEntrustId(null);
                hfEnvGkProject.setGkEntrustId(gkEntrustId);
                String unitCode = hfEnvGkProject.getUnitCode();
                HfPrjUnitBase hfPrjUnitBase = unitBaseService.getOneByCode(unitCode);
                Assert.notNull(hfPrjUnitBase, String.format("项目:【%s】不存在!", unitCode));
                hfEnvGkProject.setUnitCode(unitCode);
                hfEnvGkProject.setUnitId(hfPrjUnitBase.getId());
                hfEnvGkProject.setUnitName(hfPrjUnitBase.getUnitName());
                gkProjectService.save(hfEnvGkProject);
                String gkProjectId = hfEnvGkProject.getId();

                String standardCode = hfEnvGkProject.getStandardCode();

                HfResStandard hfResStandard = standardService.getOneByCode(standardCode);

                if (StringUtils.hasText(standardCode)) {
                    Assert.notNull(hfResStandard, String.format("依据标准:【%s】不存在!", standardCode));
                }

                String standardId = Optional.ofNullable(hfResStandard)
                    .map(HfResStandard::getId)
                    .orElse(null);
                String standardName = Optional.ofNullable(hfResStandard)
                    .map(HfResStandard::getStandardName)
                    .orElse(null);


                HfEnvTask hfEnvTask = new HfEnvTask();
                hfEnvTask.setGkProjectId(gkProjectId);
                hfEnvTask.setIzExtAssistance(ExtAssistanceConsts.NO_EXT_ASSISTANCE);
                hfEnvTask.setStandardId(standardId);
                hfEnvTask.setStandardCode(standardCode);
                hfEnvTask.setStandardName(standardName);


                hfEnvTask.setUnitId(hfPrjUnitBase.getId());
                hfEnvTask.setUnitCode(hfPrjUnitBase.getUnitCode());
                hfEnvTask.setUnitName(hfPrjUnitBase.getUnitName());
                hfEnvTask.setGkEntrustId(gkEntrustId);
                hfEnvTask.setUnitTypeName(hfPrjUnitBase.getClassifyName());
                hfEnvTask.setTestCondition(hfEnvGkProject.getTestCondition());
                hfEnvTask.setEntrustCode(entrustCode);
                hfEnvTask.setStatus(TaskConsts.TASK_STATUS_CG);
                hfEnvTask.setRowSort(i);
                String taskCode = String.format("%s%s", entrustCode, ToolKit.supplementZero(String.valueOf(i + 1), 2));
                hfEnvTask.setTaskCode(taskCode);
                taskList.add(hfEnvTask);
            }
            taskService.saveBatch(taskList);
        } catch (Exception e) {
            e.printStackTrace();
            // 重新抛出异常，让上层处理
            throw e;
        } finally {
            File zipFile = new File(zipDownloadPath);
            if (zipFile.exists()) {
                zipFile.delete();
            }
        }
    }


    @Override
    public Page<HfEnvGkEntrustVO> pageVO(Page<HfEnvGkEntrustVO> page, QueryWrapper<HfEnvGkEntrustVO> queryWrapper) {
        Page<HfEnvGkEntrustVO> hfEnvEntrustVOPage = baseMapper.pageVO(page, queryWrapper);
        List<HfEnvGkEntrustVO> records = hfEnvEntrustVOPage.getRecords();
        for (HfEnvGkEntrustVO entrustVO : records) {

        }
        return hfEnvEntrustVOPage;
    }


    @Override
    public List<HfEnvReportTaskVO> queryEntrustTaskList(String gkEntrustId) {
        List<HfEnvTask> taskList = taskService.reportListTaskByGkEntrustId(gkEntrustId);
        List<HfEnvReportTaskVO> reportTaskVOList = new ArrayList<>(taskList.size());

        for (HfEnvTask hfEnvTask : taskList) {
            String taskId = hfEnvTask.getId();
            HfEnvReportTaskVO hfEnvReportTaskVO = new HfEnvReportTaskVO();
            BeanUtils.copyProperties(hfEnvTask, hfEnvReportTaskVO);
            List<HfEnvTaskTestVO> hfEnvTaskTestVOList = testService.reportListVoByTaskId(taskId);
            hfEnvReportTaskVO.setTestList(hfEnvTaskTestVOList);
            reportTaskVOList.add(hfEnvReportTaskVO);
        }
        return reportTaskVOList;
    }

    @Override
    public HfEnvGkEntrustSaveVO queryVOById(String id) {
        HfEnvGkEntrustSaveVO hfEnvGkEntrustSaveVO = new HfEnvGkEntrustSaveVO();
        HfEnvGkEntrust hfEnvGkEntrust = this.getById(id);
        Assert.notNull(hfEnvGkEntrust, "委托数据不存在!");
        BeanUtils.copyProperties(hfEnvGkEntrust, hfEnvGkEntrustSaveVO);
        List<HfEnvGkPiece> pieceList = gkPieceService.listByGkEntrustId(id);
        hfEnvGkEntrustSaveVO.setPieceInfo(pieceList);
        List<HfEnvGkProjectSaveVO> hfEnvProjectList = gkProjectService.listVOByGkEntrustId(id);
        hfEnvGkEntrustSaveVO.setProjectInfo(hfEnvProjectList);
        List<BaseOssFiles> testOutlineList = MinioUtil.listByRefId(id, EntrustConsts.WTD_OUTLINE_REF_TYPE);
        hfEnvGkEntrustSaveVO.setTestOutlineFileList(testOutlineList);
        return hfEnvGkEntrustSaveVO;
    }


    @Override
    public boolean existEntrustCode(String entrustCode) {
        HfEnvGkEntrust hfEnvGkEntrust = this.lambdaQuery()
                .eq(HfEnvGkEntrust::getEntrustCode, entrustCode)
                .one();
        return Objects.nonNull(hfEnvGkEntrust);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.NOT_SUPPORTED)
    public Map<String, Object> batchImportDataPackage(List<String> fileIds) {
        Map<String, Object> result = new HashMap<>();
        int successCount = 0;
        int failedCount = 0;
        List<String> successFileIds = new ArrayList<>();
        List<String> failedFileIds = new ArrayList<>();
        List<String> errorMessages = new ArrayList<>();

        System.out.println("开始批量导入数据包，共" + fileIds.size() + "个文件");

        for (int i = 0; i < fileIds.size(); i++) {
            String fileId = fileIds.get(i);
            System.out.println("正在导入第" + (i + 1) + "个文件，文件ID: " + fileId.trim());

            try {
                // 为每个文件导入使用独立的事务
                importDataPackageInNewTransaction(fileId.trim());
                successCount++;
                successFileIds.add(fileId.trim());
                System.out.println("第" + (i + 1) + "个文件导入成功，文件ID: " + fileId.trim());
            } catch (Exception e) {
                failedCount++;
                failedFileIds.add(fileId.trim());

                // 获取文件名
                String fileName = getFileNameById(fileId.trim());

                // 提取更友好的错误信息
                String friendlyErrorMsg = extractFriendlyErrorMessage(e);
                String errorMsg = "文件[" + fileName + "]导入失败: " + friendlyErrorMsg;
                errorMessages.add(errorMsg);

                // 详细调试信息
                System.err.println("=== 文件导入失败详情 ===");
                System.err.println("文件ID: " + fileId.trim());
                System.err.println("文件名: " + fileName);
                System.err.println("原始异常: " + e.getClass().getSimpleName());
                System.err.println("原始错误信息: " + e.getMessage());
                System.err.println("友好错误信息: " + friendlyErrorMsg);
                System.err.println("最终错误消息: " + errorMsg);
                System.err.println("当前错误消息列表大小: " + errorMessages.size());
                System.err.println("========================");

                // 确保异常被捕获，不影响其他文件
                continue;
            }
        }

        System.out.println("批量导入完成，成功" + successCount + "个，失败" + failedCount + "个");

        result.put("successCount", successCount);
        result.put("failedCount", failedCount);
        result.put("successFileIds", successFileIds);
        result.put("failedFileIds", failedFileIds);
        result.put("errorMessages", errorMessages);

        return result;
    }

    /**
     * 在新事务中导入单个数据包
     */
    public void importDataPackageInNewTransaction(String fileId) throws Exception {
        try {
            System.out.println("开始在新事务中导入文件: " + fileId);
            importDataPackage(fileId);
            System.out.println("文件导入成功: " + fileId);
        } catch (Exception e) {
            System.err.println("新事务中导入文件失败: " + fileId + ", 错误: " + e.getMessage());
            // 重新抛出异常，让上层处理
            throw e;
        }
    }

    /**
     * 根据文件ID获取文件名
     */
    private String getFileNameById(String fileId) {
        try {
            BaseOssFiles baseOssFiles = baseOssFilesService.getById(fileId);
            if (baseOssFiles != null && baseOssFiles.getFileName() != null) {
                return baseOssFiles.getFileName();
            }
        } catch (Exception e) {
            System.err.println("获取文件名失败，文件ID: " + fileId + ", 错误: " + e.getMessage());
        }
        return "未知文件";
    }

    /**
     * 提取友好的错误信息
     */
    private String extractFriendlyErrorMessage(Exception e) {
        String message = e.getMessage();
        return message;
    }
}
